#!/bin/bash -e

usage() {
  echo "usage: $0 DOMAIN"
  echo
  echo "  DOMAIN  the domain name to add host entries for, eg. example.com"
  echo
}

if [ -z "$1" ]; then
  usage
  exit 1
fi

SERVICES="api registry vpn db s3 redis"
DOMAIN="$1"

# We need sudo to write to /etc/hosts, so first write to a temp file and then
# append all entries to hosts file.
tmp="$(mktemp --tmpdir openbalena.XXXX)"
for service in $SERVICES; do
  name="${service}.${DOMAIN}"
  if ! grep "\\s$name" /etc/hosts >/dev/null 2>&1 ; then
    echo "adding $name"
    echo "127.0.0.1 $name" >>"${tmp}"
  fi
done
# shellcheck disable=SC2024
sudo tee -a /etc/hosts >/dev/null <"${tmp}"
rm -f "${tmp}"
